package com.sxt.caculator;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class CaculatorView {
	private static char keyChar = 0;
	private static boolean keyClick = false;

	public static void main(String[] args) {
		JFrame frame = new JFrame("计算器");
		frame.setLocation(500, 200);
		frame.setVisible(true);
		frame.setSize(220, 200);
		frame.setResizable(false);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		// 主面板
		JPanel mainPanel = new JPanel();
		BorderLayout mainLayout = new BorderLayout();
		mainPanel.setLayout(mainLayout);

		// 结果框
		JTextField resultText = new JTextField(20);
		resultText.setText("0.0");
		resultText.setHorizontalAlignment(JTextField.RIGHT);
		resultText.setEditable(false);

		// 按键面板
		GridLayout numLayout = new GridLayout(4, 4);
		JPanel key = new JPanel();
		key.setLayout(numLayout);

		// 定义所需按键
		JButton b1 = new JButton("1"), b2 = new JButton("2"), b3 = new JButton(
				"3"), b4 = new JButton("4"), b5 = new JButton("5"), b6 = new JButton(
				"6"), b7 = new JButton("7"), b8 = new JButton("8"), b9 = new JButton(
				"9"), b0 = new JButton("0"), bPoint = new JButton("."), bAdd = new JButton(
				"+"), bReduce = new JButton("-"), bRide = new JButton("*"), bDivide = new JButton(
				"/"), bResult = new JButton("=");

		// 添加按键
		key.add(b1);
		key.add(b2);
		key.add(b3);
		key.add(bAdd);
		key.add(b4);
		key.add(b5);
		key.add(b6);
		key.add(bReduce);
		key.add(b7);
		key.add(b8);
		key.add(b9);
		key.add(bRide);
		key.add(bPoint);
		key.add(b0);
		key.add(bResult);
		key.add(bDivide);

		addListioner(b1, '1');
		addListioner(bReduce, '-');

		// 计时器
		final JLabel timer = new JLabel();
		Timer time = new Timer();
		time.schedule(new TimerTask() {
			@Override
			public void run() {
				timer.setText("当前时间："
						+ new SimpleDateFormat("HH:mm:ss").format(new Date()));
			}
		}, 0, 1000);
		timer.setHorizontalAlignment(JLabel.CENTER);

		mainPanel.add(resultText, BorderLayout.NORTH);
		mainPanel.add(key, BorderLayout.CENTER);
		mainPanel.add(timer, BorderLayout.SOUTH);
		frame.add(mainPanel);
		frame.pack();
	}

	public static void addListioner(JButton b, final char keyChar) {

		b.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				// TODO Auto-generated method stub
				super.mouseClicked(e);
				CaculatorView.keyClick = true;
				CaculatorView.keyChar = keyChar;
				CaculatorView.keyClick = false;
			}
		});
	}
}